<?php
if (! defined ( 'BASEPATH' ))
    exit ( 'No direct script access allowed' );

class RekHistory extends Controller {
    public function __construct() {
        parent::__construct ();
        $this->_data = array ();
        $this->load->model ( 'rekhistory_model' );
        isController('akuntansi','rekHistory');
    }
    protected function _view($template, $data = array(), $result = false) {
        if ($data && is_array ( $data )) {
            return $this->load->view ( $template, $data, $result );
        }
        return $this->load->view ( $template, $this->_data, $result );
    }
    public function index() {
        redirect ( 'akuntansi/rekHistory/view' );
    }
    protected function _executeView() {
        $array = $this->uri->uri_to_assoc ( 3, array ('id', 'action' ) );
        // delete action
        if (isAccess('akuntansi','rekhistory','delete') && $array ['action'] == 'delete' && $array ['id']) {
            if ($this->rekhistory_model->delete($array['id'])) {
                $this->_data['errorMessage'] =  'Berhasil Delete History Rekening' ;
                $this->_data['isSuccess'] =  true ;
            } else {
                $this->_data['errorMessage'] =  'Gagal Delete History Rekening' ;
            }
        }
    }
    public function view() {
    	if (! isAccess ( 'akuntansi', 'rekhistory', 'view'))
            redirect (); 
        $array = $this->uri->uri_to_assoc ( 3, array ('id', 'year', 'month', 'tipe', 'action', 'page' ) );
        $this->_executeView ();
        $array['page'] = (int) $array['page'];

        //List Rek Tipe
        $this->load->model('rektipe_model');
        $listTipe = $this->config->item('listRekTipe');
        
        $listRekTipe = array();
        if($listTipe) foreach($listTipe as $tipe) {
        	$listRek[$tipe] = $this->rektipe_model->getList (100, 0, array('rekTipe'=>$tipe));

        	if($listRek[$tipe]) foreach($listRek[$tipe] as $k=>$v) {
        		$listRekTipe[$tipe][$v['rekTipeId']] = $v['rekTipeNama'];
        	}
        }
        $this->_data['listRekTipe'] = $listRekTipe;
        
        //Uri
        $array['tipe'] = !empty($array['tipe']) ? $array['tipe'] : 'all';
        $array['year'] = !empty($array['year']) ? $array['year'] : 'all';
        $array['month'] = !empty($array['month']) ? $array['month'] : 'all';
        
        //Where
        $where = array();
        if( !empty($array['year']) && $array['year'] != 'all' )
        	$where['historyPeriodeTahun'] = $array['year'];
        if( !empty($array['month']) && $array['month'] != 'all' )
        	$where['historyPeriodeBulan'] = $array['month'];	
        if( !empty($array['tipe']) && $array['tipe'] != 'all' )
        	$where['rekTipeId'] = $array['tipe'];
     	
        $total = 0;
        if( $array['year'] != 'all' && $array['month'] != 'all' )	
        	$total = $this->rekhistory_model->getCount($where);
        	
        if (($array['page'] + 1) > $total)
            $array['page'] = 0;
            
        $this->load->library('pagination');    
        $limit = $this->config->item('klinik_limit');
        $config = $this->config->item('paging');
        $config['base_url'] = site_url('akuntansi/rekHistory/view/year/'.$array['year'].'/month/'.$array['month'].'/tipe/'.$array['tipe'].'/page/');
        $config['uri_segment'] = 10;
        $config['total_rows'] = $total;
        $config['per_page'] = $limit;
        
        $this->pagination->initialize($config);
        $this->_data['paging'] =  $this->pagination->create_links();
        
        $dataView = array();
        if( $array['year'] != 'all' && $array['month'] != 'all' )
        	$dataView = $this->rekhistory_model->getList($limit, $array['page'], $where);
        
        $this->_data['dataView'] = $dataView;

        $this->_data['uri_to_assoc'] = $array;
        $this->_view ( 'akuntansi/rekHistoryView' );
    }

    protected function _executeEdit() {
        $array = $this->uri->uri_to_assoc ( 3, array ('id', 'year', 'month', 'tipe', 'action' ) );
        
        if ($this->input->post ( 'submit' ) == 'Simpan' && $this->input->post ( 'kirim' ) == 'kirim') {
            $historyRealisasi = trim ( $this->input->post ( 'historyRealisasi' ) );
            $historyRealisasi = str_replace(',', '', $historyRealisasi);
            
        	$historyAnggaran = trim ( $this->input->post ( 'historyAnggaran' ) );
        	$historyAnggaran = str_replace(',', '', $historyAnggaran);
        	
        	$historySelisih = trim ( $this->input->post ( 'historySelisih' ) );
        	$historySelisih = str_replace(',', '', $historySelisih);
        	
        	$historyProsentase = trim ( $this->input->post ( 'historyProsentase' ) );
			$historyProsentase = str_replace(',', '', $historyProsentase);
			
            $data = array ();
            $data ['historyRealisasi'] = $historyRealisasi;
            $data ['historyAnggaran'] = $historyAnggaran;
//            $data ['historySelisih'] = $historySelisih;
//            $data ['historyProsentase'] = $historyProsentase;

            $errors = array ();
            if (!isset ( $historyRealisasi ))
                $errors [] = 'Input Nilai Realisasi';
            if (!isset ( $historyAnggaran ))
                $errors [] = 'Input Nilai Anggaran';
//            if (!isset ( $historySelisih ))
//                $errors [] = 'Input Nilai Selisih';
//            if (!isset ( $historyProsentase ))
//                $errors [] = 'Input Nilai Prosentase';

            if ($errors) {
                $this->_data['errorMessage'] =  implode ( '<br />', $errors ) ;
            } else {
            	$this->load->model('rekening_model');
            	$getRekHistory = $this->rekhistory_model->get($array['id']);
            	$rekId = get_data($getRekHistory,'rekeningId');
            	
            	$getDetail = $this->rekening_model->get($rekId);
            	
            	$data['historySelisih'] = 0;
	            $data['historyProsentase'] = 0;
	            	
            	//Pendapatan
            	if( get_data($getDetail,'rekTipe') == 'Pendapatan' ) {
	            	$data['historySelisih'] = $data['historyRealisasi'] - $data['historyAnggaran'];
	            	if($data['historyAnggaran'] > 0) {
	            		
	            		//Defisit
	            		if( $data['historySelisih'] < 0 ) {
	            			$historySelisih = $data['historySelisih'] * -1;
	            			$data['historyProsentase'] = round($historySelisih / $data['historyAnggaran'] * 100);	
	            			$data['historyProsentase'] = $data['historyProsentase'] * -1;

	            		//Surplus
	            		} else {
	            			$data['historyProsentase'] = round($data['historySelisih'] / $data['historyAnggaran'] * 100);	
	            		}
	            		
	            	}
	            	
	            //Beban		
            	} elseif( get_data($getDetail,'rekTipe') == 'Beban' ) {
            		$data['historySelisih'] = $data['historyAnggaran'] - $data['historyRealisasi'];
	            	if($data['historyAnggaran'] > 0) {
	            		
	            		//Defisit
	            		if( $data['historySelisih'] < 0 ) {
	            			$historySelisih = $data['historySelisih'] * -1;
	            			$data['historyProsentase'] = round($historySelisih / $data['historyAnggaran'] * 100);	
	            			$data['historyProsentase'] = $data['historyProsentase'] * -1;

	            		//Surplus
	            		} else {
	            			$data['historyProsentase'] = round($data['historySelisih'] / $data['historyAnggaran'] * 100);	
	            		}
	            		
	            	}	
            	}
            	//End
            	
            	$this->rekhistory_model->update ( $array['id'], $data );
                $this->_data['errorMessage'] =  'Berhasil Edit History Rekening' ;
                unset($_POST);
                $this->_data['isSuccess'] =  true ;
                
                $rekHistory = $this->rekhistory_model->get ( $array['id'] );
                $this->_data['dataEdit'] = $rekHistory;    
            }       
        }    
    }

    public function edit() {
    	if (! isAccess ( 'akuntansi', 'rekHistory', 'edit'))
            redirect (); 
        $array = $this->uri->uri_to_assoc ( 3, array ('id', 'year', 'month', 'tipe' ) );
        if ( !$array ['id'] || !$array ['year'] || !$array ['month'] || !$array ['tipe'] )
            show_404 ();
            
        $dataHistory = $this->rekhistory_model->get ( $array ['id'] );
        $this->_data['dataEdit'] = $dataHistory;    
        if (! $dataHistory)
            show_404 ();
        
        $this->_executeEdit();
        $this->_data['uri_to_assoc'] = $array;
        $this->_view ( 'akuntansi/rekHistoryEdit' );
    }
    
	public function exportPdf() {
    	if (! isAccess ( 'akuntansi', 'rekrincian', 'exportexcel'))
            redirect (); 
        $array = $this->uri->uri_to_assoc ( 3, array ('year', 'month', 'tipe') );
        if ( !$array ['year'] || !$array ['month'] || !$array ['tipe'] )
            show_404 ();
            
        //Data General
        $this->load->helper('inflector');
        $this->load->model('rekening_model');
        
	    $dataRek = $this->rekening_model->get($array ['tipe']);    

	    //Data
        $where = array();
        $where['historyPeriodeTahun'] = $array['year'];
        $where['historyPeriodeBulan'] = $array['month'];	
        $where['rekTipeId'] = $array['tipe'];
        $dataView = $this->rekhistory_model->getList(100, 0, $where);
	    
        //Template PDF
        $content = '<page backtop="14mm" backbottom="14mm" pagegroup="new">
				    <page_header>
					<table style="width:100%;">
					    <tr>
							<td style="width:70%;">'.$this->lang->line('global_title').'</td>
							<td style="width:30%;">Rincian : '.get_data($dataRek,'rekeningNama').'</td>
					    </tr>
						<tr>
							<td>'.$this->lang->line('global_title_cab').' </td>
							<td>Periode : '.monthName(get_data($array,'month')).' '.get_data($array,'year').'</td>
					    </tr>
					    <tr>
							<td>'.$this->lang->line('global_alamat_cab').'</td>
							<td></td>
					    </tr>
					</table>
				    </page_header>
				    <page_footer>
					<table style="width: 100%;">
					    <tr>
						<td style="text-align: right">
						    Page : [[page_cu]]/[[page_nb]]
						</td>
					    </tr>
					</table>
				    </page_footer>
				</page><br />';
	
	    $content .= '<table border="1" style="width:100%;">
				    <thead style="text-align:center;height:100px;">
					<tr height="50">
					    <th style="width:5%" rowspan="2">No</th>
					    <th style="width:35%" rowspan="2">Nama Rekening</th>
					    <th style="width:15%" colspan="2">Realisasi</th>
					    <th style="width:15%" colspan="2">Anggaran</th>
					    <th style="width:15%" colspan="2">Selisih</th>
					    <th style="width:10%" colspan="2">Prosentase</th>
					</tr>
					<tr height="50" style="border:none;">					    
						<th style="width:2%">&nbsp;</th><th style="width:13%"></th>
					   	<th style="width:2%"></th><th style="width:13%"></th>
					    <th style="width:2%"></th><th style="width:13%"></th>					    
					    <th style="width:8%"></th>
						<th style="width:2%"></th>
					</tr>
				    </thead>
				    <tbody style="text-align:center;">';

	    $no=1;
	    if($dataView) foreach ($dataView as $row) {
			$content .= '<tr>
							<td>'.$no.'</td>
							<td align="left">'.$row['rekeningNama'].'</td>
							<td>Rp. </td>
							<td align="right">'.number_format($row['historyRealisasi']).'</td>
							
							<td>Rp. </td>
							<td align="right">'.number_format($row['historyAnggaran']).'</td>
							
							<td>Rp. </td>
							<td align="right">'.number_format($row['historySelisih']).'</td>
							
							<td>'.number_format($row['historyProsentase']).'</td>

							<td>%</td>		    		    </tr>';
			$no++;
	    }
	   
	    $content .= '</tbody>
	                 </table>';
		
	    //Convert to PDF
	    $this->load->library('html2pdf/html2pdf');
	    $html2pdf = new HTML2PDF('L', 'A4');
	    $html2pdf->pdf->SetDisplayMode('fullpage');
	    $html2pdf->writeHTML($content, FALSE);
	    $html2pdf->Output( underscore($dataRek['rekeningNama']).'_'.monthName(get_data($array,'month')).'_'.get_data($array,'year').'.pdf' );
    }
    
}